import logging
from logging.handlers import RotatingFileHandler

from flask import Flask
# 可以用来指定 session 保存的位置
from flask import g
from flask import render_template
from flask.ext.session import Session
from flask.ext.sqlalchemy import SQLAlchemy
from flask.ext.wtf import CSRFProtect
from flask.ext.wtf.csrf import generate_csrf
from redis import StrictRedis

from config import config



db = SQLAlchemy()
redis_store: StrictRedis = None

def setup_log(config_name):
    # 设置日志的记录等级
    logging.basicConfig(level=config[config_name].DEBUG)  # 调试debug级
    # 创建日志记录器，指明日志保存的路径、每个日志文件的最大大小、保存的日志文件个数上限
    file_log_handler = RotatingFileHandler("logs/log", maxBytes=1024 * 1024 * 100, backupCount=10)
    # 创建日志记录的格式 日志等级 输入日志信息的文件名 行数 日志信息
    formatter = logging.Formatter('%(levelname)s %(filename)s:%(lineno)d %(message)s')
    # 为刚创建的日志记录器设置日志记录格式
    file_log_handler.setFormatter(formatter)
    # 为全局的日志工具对象（flask app使用的）添加日志记录器
    logging.getLogger().addHandler(file_log_handler)


def get_app(config_name):
    setup_log(config_name)

    Config = config['test']
    setup_log(config_name)
    app = Flask(__name__)
    app.config.from_object(Config)
    
    # 初始化数据库
    db.init_app(app)
    # db = SQLAlchemy(app)
    redis_store = StrictRedis(host=Config.REDIS_HOST, port=Config.REDIS_PORT, decode_responses=True)
    CSRFProtect(app)
    Session(app)
    
    from application.modules.index import index_blue
    app.register_blueprint(index_blue)
    from application.modules.playgame import play_blue
    app.register_blueprint(play_blue)
    from application.modules.rooms import rooms_blue
    app.register_blueprint(rooms_blue)
    from application.modules.ranking import ranking_blue
    app.register_blueprint(ranking_blue)
    return app